// pod.go
package controllers

import (
	//"encoding/json"
	//"fmt"
	"log"
	//"myk8s/common"
	m "myk8s/models"
	"strings"

	beego "github.com/beego/beego/v2/server/web"
	"github.com/tidwall/gjson"
)

type PodController struct {
	beego.Controller
}

func (this *PodController) List() {
	clusterId := this.GetString("clusterId")
	nameSpace := this.GetString("nameSpace")
	deployName := this.GetString("deployName")
	podName := this.GetString("podName")
	nodeName := this.GetString("nodeName")
	labels := this.GetString("labels")
	labelsKV := strings.Split(labels, ":") //yaml里没有对应的appname,deployment不会传递过来
	var labelsKey, labelsValue string
	if len(labelsKV) == 2 {
		labelsKey = labelsKV[0]
		labelsValue = labelsKV[1]
	}
	podList, err := m.PodList(clusterId, nameSpace, deployName, podName, labelsKey, labelsValue, nodeName)
	msg := "success"
	code := 0
	if err != nil {
		log.Println(err)
		code = -1
		msg = err.Error()
	}

	count := len(podList)
	this.Data["json"] = &map[string]interface{}{"code": code, "msg": msg, "count": count, "data": &podList}
	this.ServeJSON()
}

func (this *PodController) ContainerList() {
	clusterId := this.GetString("clusterId")
	nameSpace := this.GetString("nameSpace")
	podName := this.GetString("podName")
	code := 0
	msg := "success"
	xList, err := m.PodContainerList(clusterId, nameSpace, podName)
	if err != nil {
		code = -1
		msg = err.Error()
		log.Printf("[ERROR] ContainerList error:%s\n", err)
	}
	this.Data["json"] = &map[string]interface{}{"code": code, "msg": msg, "count": len(xList), "data": &xList}
	this.ServeJSON()
}

func (this *PodController) Log() {
	clusterId := this.GetString("clusterId")
	nameSpace := this.GetString("nameSpace")
	podName := this.GetString("podName")
	download, _ := this.GetBool("download")
	container := this.GetString("container")
	logLine, _ := this.GetInt64("logLine")

	if this.Ctx.Input.Method() == "POST" {
		gp := gjson.ParseBytes(this.Ctx.Input.RequestBody)
		podName = gp.Get("podName").String()
		logLine = gp.Get("logLine").Int()
		container = gp.Get("container").String()
	}
	if logLine == 0 { //没设置行时，默认为100
		logLine = 100
	}
	if download { //当日志时下载时，不限制行数
		logLine = 0
	}
	log := m.PodLog(clusterId, nameSpace, podName, container, logLine)
	this.Ctx.WriteString(log)
}
